﻿using System.Collections.Generic;
using System.Web;
using System;
using System.Net.Mail;
using System.Runtime.Remoting.Messaging;

namespace PayRoller.Code
{
    public class PDFAndMail
    {
        public static void CreatePDFAndSendMail(string pageURL, string attachmentPath, string receiverMail,string subject,string body)
        {
            //1.生成附件
            MailInfo mailInfo = new MailInfo(receiverMail,subject,body);
            CreatePDFHandler createPDFDelegate = new CreatePDFHandler(PDFHelper.CreatPdf);
            createPDFDelegate.BeginInvoke(pageURL, attachmentPath, new AsyncCallback(CreatePDFCallbackMethod), mailInfo);
        }

        private static void CreatePDFCallbackMethod(IAsyncResult ar)
        {
            //1.获取生成的PDF文件的名称
            CreatePDFHandler createPDFDelegate = ((AsyncResult)ar).AsyncDelegate as CreatePDFHandler;
            string pdfFileName = createPDFDelegate.EndInvoke(ar);
            MailInfo mailInfo = ar.AsyncState as MailInfo;
            if (mailInfo == null)
            {
                return;
            }

            string receiverMail = mailInfo.ReceiverMail;
            string subject = mailInfo.Subject;
            string body = mailInfo.Body;

            //2.发送邮件
            bool isBodyHtml = true;

            if (string.IsNullOrEmpty(receiverMail) == false)
            {
                SendMailHandler sendMailHandler = new SendMailHandler(MailHelper.SendMail);
                Attachment att = new Attachment(pdfFileName);
                List<Attachment> attList = new List<Attachment>();
                attList.Add(att);
                sendMailHandler.BeginInvoke(receiverMail, subject, body, isBodyHtml, attList, new AsyncCallback(SendMailCallbackMethod), null);
            }
        }

        private static void SendMailCallbackMethod(IAsyncResult ar)
        {
            //do nothing;
        }

        private class MailInfo
        {
            public MailInfo(string receiverMail, string subject, string body)
            {
                this.body = body;
                this.subject = subject;
                this.receiverMail = receiverMail;
            }

            private string receiverMail = string.Empty;
            public string ReceiverMail
            {
                get { return this.receiverMail; }
                set { this.receiverMail = value; }
            }

            private string subject = string.Empty;
            public string Subject
            {
                get { return this.receiverMail; }
                set { this.receiverMail = value; }
            }

            private string body = string.Empty;
            public string Body
            {
                get { return this.body; }
                set { this.body = value; }
            }
        }
    }
}